package top.hzy520.personalblog.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import top.hzy520.personalblog.service.BlogService;
import top.hzy520.personalblog.service.TagService;
import top.hzy520.personalblog.service.TypeService;

@Controller
public class IndexController {

    @Autowired
    private TypeService typeService;

    @Autowired
    private TagService tagService;

    @Autowired
    private BlogService blogService;

      @GetMapping("/")
    public  String index(@PageableDefault(sort = {"updateTime"},direction = Sort.Direction.DESC,size = 8) Pageable pageable, Model model){
       model.addAttribute("page",blogService.listBlog(pageable));
       model.addAttribute("types",typeService.listType(6));
       model.addAttribute("tags",tagService.listTag(10));
       model.addAttribute("recommendBlogs",blogService.listBlog(8));
        return "index";
    }

    @PostMapping("/search")
    public  String search(@PageableDefault(sort = {"updateTime"},direction = Sort.Direction.DESC,size = 8) Pageable pageable, Model model,@RequestParam String query){
      model.addAttribute("page",blogService.listBlog("%"+query+"%",pageable));
        model.addAttribute("query",query);
     return "search";
    }

    @GetMapping("/blog/{id}")
    public String blog(@PathVariable Long id,Model model){
        model.addAttribute("blog",blogService.getAndConvert(id));
     return "blog";
    }
}
